import { StyleSheet, Text, View, ScrollView, Pressable } from 'react-native';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Picker } from 'react-native-wheel-pick';
import { useNavigation, useRoute } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { NavBarHeader } from '~/components';
import { observer, deviceStore } from '~/store';
import { px2dp, scale, width } from '~/utils/px2dp';
import { setBleColock } from '~/utils/ble/application';

const hourData = Array.from({ length: 24 }, (_, i) => String(i + 1).padStart(2, '0'));
const mineData = Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0'));
const padZero = (num) => (num < 10 ? `0${num}` : num);

export default observer(() => {
    const { colockData } = deviceStore;
    const { t } = useTranslation();
    const router: any = useRoute();
    const navigation: any = useNavigation();
    const { selectIndex } = router.params || {};
    const [itemList, setItemList] = useState<any>([]);
    const [hour, setHour] = useState<any>(0);
    const [mine, setMine] = useState<any>(0);
    const [repeatData, setRepeatData] = useState<any>([
        { value: 1, name: t('ColockDetailes.t4'), checked: false },
        { value: 2, name: t('ColockDetailes.t5'), checked: false },
        { value: 4, name: t('ColockDetailes.t6'), checked: false },
        { value: 8, name: t('ColockDetailes.t7'), checked: false },
        { value: 16, name: t('ColockDetailes.t8'), checked: false },
        { value: 32, name: t('ColockDetailes.t9'), checked: false },
        { value: 64, name: t('ColockDetailes.t10'), checked: false },
    ]);
    // 计算周期--回显
    const computingcycles = (numdata) => {
        let num = Number(numdata);
        let numList: any = [];
        if (num >= 64) {
            numList.push(6);
            num -= 64;
        }
        if (num >= 32) {
            numList.push(5);
            num -= 32;
        }
        if (num >= 16) {
            numList.push(4);
            num -= 16;
        }
        if (num >= 8) {
            numList.push(3);
            num -= 8;
        }
        if (num >= 4) {
            numList.push(2);
            num -= 4;
        }
        if (num >= 2) {
            numList.push(1);
            num -= 2;
        }
        if (num >= 1) {
            numList.push(0);
            num -= 1;
        }
        return numList.reverse();
    };
    const getData = () => {
        let data = [...repeatData]; // 避免直接修改 state
        let items: any = [];

        let cycle = computingcycles(colockData[selectIndex == 0 ? 1 : selectIndex == 1 ? 5 : 9]);

        cycle.forEach((e) => {
            data[e].checked = true;
            items.push(data[e].value);
        });

        setRepeatData(data);
        setItemList(items);

        const hh = padZero(colockData[selectIndex == 0 ? 2 : selectIndex == 1 ? 6 : 10]);
        const mm = padZero(colockData[selectIndex == 0 ? 3 : selectIndex == 1 ? 7 : 11]);
        setHour(hh);
        setMine(mm);
    };
    // 全选或者取消全选
    const selectAll = () => {
        const isAllSelected = repeatData.every((item) => item.checked);
        setItemList(!isAllSelected ? [1, 2, 4, 8, 16, 32, 64] : []);
        const newData = repeatData.map((item) => ({
            ...item,
            checked: !isAllSelected,
        }));
        setRepeatData(newData);
    };

    // 单个点击选择
    const toggleItem = (index, value) => {
        const newData = [...repeatData];
        newData[index].checked = !newData[index].checked;
        setRepeatData(newData);
        setItemList((prevList) => {
            if (newData[index].checked) {
                return [...prevList, value];
            } else {
                return prevList.filter((item) => item !== value);
            }
        });
    };
    const submit = () => {
        let datalist = 0;
        itemList.forEach((e) => {
            datalist += Number(e);
        });
        colockData.splice(selectIndex == 0 ? 1 : selectIndex == 1 ? 5 : 9, 3, datalist, parseInt(hour), parseInt(mine));
        setBleColock(router.params, colockData);
        setTimeout(() => {
            navigation.goBack();
        }, 200);
    };
    useEffect(() => {
        getData();
    }, []);
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('ColockDetailes.title')} />
            <ScrollView contentContainerStyle={styles.contentStyle}>
                <Text style={styles.title}>{t('ColockDetailes.title')}</Text>
                <View style={[styles.row]}>
                    <Picker
                        style={styles.pciker}
                        selectedValue={hour.toString()}
                        itemStyle={styles.itemStyle}
                        textSize={px2dp(40)}
                        pickerData={hourData}
                        onValueChange={(index) => {
                            setHour(index);
                        }}
                    />
                    <Picker
                        style={styles.pciker}
                        itemStyle={styles.itemStyle}
                        textSize={px2dp(40)}
                        selectedValue={mine.toString()}
                        pickerData={mineData}
                        onValueChange={(index) => {
                            setMine(index);
                        }}
                    />
                </View>
                <View style={styles.card}>
                    <View style={[styles.row, { justifyContent: 'space-between' }]}>
                        <Text style={styles.card_title}>重复</Text>
                        <Pressable onPress={selectAll}>
                            <Text style={[styles.card_title, { color: '#25C8C8' }]}>{t('ColockDetailes.t1')}</Text>
                        </Pressable>
                    </View>
                    {repeatData.map((item, index) => {
                        return (
                            <Pressable
                                key={index}
                                style={[styles.listItem, styles.row]}
                                onPress={() => toggleItem(index, item.value)}>
                                <Text style={styles.listName}>{item.name}</Text>
                                <Icon
                                    name={'checkmark-circle'}
                                    size={px2dp(50)}
                                    color={item.checked ? '#25C8C8' : '#a4a4a4'}></Icon>
                            </Pressable>
                        );
                    })}
                </View>
                <View style={[styles.bottom, styles.row]}>
                    <Pressable style={[styles.bt, { backgroundColor: '#a4a4a4' }]} onPress={() => navigation.goBack()}>
                        <Text style={[styles.bt_text]}>{t('ColockDetailes.t2')}</Text>
                    </Pressable>
                    <Pressable style={[styles.bt]} onPress={submit}>
                        <Text style={[styles.bt_text]}>{t('ColockDetailes.t3')}</Text>
                    </Pressable>
                </View>
            </ScrollView>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        padding: px2dp(24),
        paddingBottom: '20%',
    },
    pciker: {
        width: (width - px2dp(48)) / 2,
        backgroundColor: '#fff',
    },
    itemStyle: {
        height: px2dp(420),
    },
    title: {
        color: '#000',
        fontSize: scale(36),
        fontWeight: 'bold',
        marginBottom: px2dp(24),
    },
    card: {
        backgroundColor: '#fff',
        padding: px2dp(32),
        paddingVertical: px2dp(24),
        borderRadius: px2dp(12),
        marginTop: px2dp(24),
    },
    card_title: {
        fontSize: scale(30),
        color: '#191919',
    },
    listItem: {
        justifyContent: 'space-between',
        marginTop: px2dp(24),
    },
    listName: {
        color: '#a4a4a4',
        fontSize: scale(32),
        marginTop: px2dp(24),
    },
    bottom: {
        marginTop: px2dp(64),
        justifyContent: 'space-between',
    },
    bt: {
        height: px2dp(88),
        borderRadius: px2dp(44),
        justifyContent: 'center',
        alignItems: 'center',
        marginHorizontal: px2dp(32),
        backgroundColor: '#25C8C8',
        width: '40%',
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
});
